package com.rchat.pocmini.activity.adapter;


import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.airtalkee.sdk.AirtalkeeAccount;
import com.aso.common.http.bean.BaseBean;
import com.aso.common.http.delegate.HttpCallbackImpl;
import com.aso.common.http.utils.HttpUtils;
import com.rchat.pocmini.R;
import com.rchat.pocmini.bean.SearchGroupBean;
import com.rchat.pocmini.global.HttpCodeGlobal;
import com.rchat.pocmini.global.RequestParam;
import com.rchat.pocmini.global.UrlsGlobal;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ljd on 2017/3/7.
 */

public class SearchGroupResultListViewAdapter extends BaseAdapter {

    private LayoutInflater inflater;
    private ArrayList<SearchGroupBean.DataBean.GroupsBean.GroupBean> data;
    private Context context;
//    private Handler handler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case 1:
//                    String backJson = (String) msg.obj;
//                    try {
//                        if (null == backJson) {
//                            Toast.makeText(context, "服务器请求超时", Toast.LENGTH_SHORT).show();
//                            return;
//                        }
//                        JSONObject json = new JSONObject(backJson);
//                        if (json.getString("code").equals("421")) {
//                            Toast.makeText(context, "您已在该群组中", Toast.LENGTH_SHORT).show();
//                        } else if (json.getString("code").equals("200")) {
//                            Toast.makeText(context, "申请成功，等待该频道的群主通过", Toast.LENGTH_SHORT).show();
//                        } else {
//                            Toast.makeText(context, "申请失败，请检查您的网络", Toast.LENGTH_SHORT).show();
//                        }
//                    } catch (JSONException e) {
//                        Toast.makeText(context, "申请失败，请检查您的网络", Toast.LENGTH_SHORT).show();
//                        e.printStackTrace();
//                    }
//            }
//        }
//    };

    public SearchGroupResultListViewAdapter(Context context, ArrayList<SearchGroupBean.DataBean.GroupsBean.GroupBean> data) {
        this.data = data;
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final ViewHolder holder;
        if (null == convertView) {
            convertView = inflater.inflate(R.layout.search_group_result_list_view_item_layout, null);
            holder = new ViewHolder();
            holder.groupName = (TextView) convertView.findViewById(R.id.tv_group_name);
            holder.groupId = (TextView) convertView.findViewById(R.id.tv_group_id);
            holder.btnJoin = (Button) convertView.findViewById(R.id.btn_join);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }


        final SearchGroupBean.DataBean.GroupsBean.GroupBean bean = data.get(position);
        holder.groupId.setText("ID:" + bean.getGroupId());
        holder.groupName.setText(bean.getGroupName());

        if (bean.isApply()) {
            holder.btnJoin.setBackgroundColor(Color.parseColor("#dadbdd"));
            holder.btnJoin.setText("已申请");
        } else {
            holder.btnJoin.setBackgroundColor(Color.parseColor("#1EC0F7"));
            holder.btnJoin.setText("申请");
        }

        holder.btnJoin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //申请加入群组处理
                applyGroup(bean.getGroupId(), AirtalkeeAccount.getInstance().getUserId());
                bean.setApply(true);
                notifyDataSetChanged();
            }
        });
        return convertView;
    }

    private static class ViewHolder {
        private TextView groupName;
        private TextView groupId;
        private Button btnJoin;
    }

    private void applyGroup(String groupName, String userName) {

        Map<String, String> param = new HashMap<>();
        param.put("userName", userName);
        param.put("groupId", groupName);
        //body = {"code":1025,"data":{"platform":1,"version":"1.0","enterprise":1,"groupId":"C20040","userName":"111110000118"}}
        String body = RequestParam.requestRootParam(HttpCodeGlobal.REQ_CODE_1025, param);

        HttpUtils.postAsyn(UrlsGlobal.getUrl(UrlsGlobal.APPLY_JOIN_GROUP), body, new HttpCallbackImpl<SearchGroupBean>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(SearchGroupBean searchGroupBean) {
                Toast.makeText(context, "申请成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailureResult(BaseBean bean) {
                switch (bean.getCode()) {
                    case HttpCodeGlobal.RES_CODE_421 + "":
                        Toast.makeText(context, "已经在群组中", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        Toast.makeText(context, bean.getDesc(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onFinish() {

            }
        });
    }

//    /**
//     * 生成申请加入群组的请求json
//     *
//     * @param userName 创建者
//     * @return json
//     */
//    private String applyJoinGroupJson(String groupId, String userName) {
//        StringBuilder sb = new StringBuilder();
//        sb.append("{").append("\"code\"").append(":").append("\"1025\"").append(",")
//                .append("\"signature\"").append(":").append("\"aaa\"").append(",")
//                .append("\"data\"").append(":").append("{")
//                .append("\"groupId\"").append(":").append("\"").append(groupId).append("\",")
//                .append("\"userName\"").append(":").append("\"").append(userName).append("\"")
//                .append("}")
//                .append("}");
//        return sb.toString();
//    }
//
//
//    /**
//     * 执行申请加入群组的线程
//     *
//     * @param requestJson 创建群组请求json
//     */
//    private void startJoinGroupThread(final String requestJson) {
//        Thread thread = new Thread() {
//            @Override
//            public void run() {
//                String backJson = HttpUtil.httpConnect(HttpUtil.APPLY_JOIN_GROUP, requestJson, HttpUtil.HTTP_POST);
//                Message message = new Message();
//                message.what = 1;
//                message.obj = backJson;
//                handler.sendMessage(message);
//            }
//        };
//        thread.start();
//    }
}
